<template>
  <div class="product-bom-list">
    <div class="product-bom-list__header g-flex-between-center">
      <div class="g-flex-start-center">
        <template v-if="!props.readonly">
          <el-button class="g-mr12" type="primary" @click="handleAddBom()"
            ><CIcon class="g-mr4" type="c-xian-xinjian"></CIcon>新增物料</el-button
          >
          <template v-if="isBomImported === true">
            <el-button type="default" @click="handleClearData"
              ><CIcon class="g-mr4" type="c-xian-qingkong"></CIcon>清空数据</el-button
            >
            <el-button type="primary" @click="handleExport" v-if="isBomImported === true">
              <CIcon class="g-mr4" type="c-xian-xiazai"></CIcon>
              下载BOM清单</el-button
            >
          </template>
          <template v-else>
            <CFileUploadAndTempDownload
              :uploadApi="importModelBomAction"
              :params="{ formNo }"
              @success="handleRefresh"
              :templateUrl="commonConfig.SUPPLIER_PRODUCT_BOM_TEMPLATE_URL"
              uploadText="导入零部件BOM"
            />
          </template>
        </template>
      </div>
      <div class="g-flex-start-center">BOM重量：{{ empty(bomTotalDosage) }}kg</div>
    </div>
    <CTable
      ref="tableRef"
      rowKey="nodeNo"
      :loadData="loadData"
      :tableFieldsSetting="props.readonly ? tableFieldsSettingReadonly : tableFieldsSetting"
      :extraTableOption="extraTableOption"
      :pagination="false"
      border
    >
      <template #dosageHeaderSlot>
        <div class="g-flex-center-center">
          <span>用量</span>
          <el-tooltip placement="top">
            <template #content>
              <div>
                <p>推荐选用单位：</p>
                <p class="g-ml2">• 重量类：kg、g、mg</p>
                <p class="g-ml2">• 体积类：m3、L、mL</p>
                <p class="g-ml2">• 面积类：m2、cm2</p>
                <p class="g-ml2">• 长度类：m、cm、mm</p>
                <p class="g-ml2">• 数量类：pcs，请勿填写“个”、“台”等</p>
              </div>
            </template>
            <CIcon class="g-ml4 g-cur-poi dosage-header-icon" type="c-xian-shuoming"></CIcon>
          </el-tooltip>
        </div>
      </template>
      <template #dosageSlot="{ scope }">
        {{ scope.row.dosage ? scope.row.dosage + scope.row.unit : '-' }}
      </template>
      <template #weightSlot="{ scope }">
        <span v-if="isWeightUnit(scope.row.unit)">-</span>
        <span v-else>{{ scope.row.weight ? scope.row.weight + scope.row.weightUnit : '-' }}</span>
      </template>
      <template #op="{ scope }">
        <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)"></CTableButtonGroup>
      </template>
    </CTable>
    <MaterialDialog
      v-model:visible="materialDialogVisible"
      :read-only="props.readonly"
      :formNo="formNo"
      :nodeItem="nodeItem"
      @refresh="handleRefresh"
    ></MaterialDialog>
  </div>
</template>

<script lang="ts" setup name="ProductBomList">
import { withDefaults, defineProps, ref } from 'vue';
import { useMessage } from '@/hooks/useMessage';
import { CTable, TableFieldsSettingType } from '@/components/CTable';
import { MaterialDialog } from './components/MaterialDialog/index';
import { CTableButtonGroup } from '@/components/CTable';
import type { TableButtonItem } from '@/components/CTable';

import {
  importModelBomAction,
  getSupplierListBom,
  postClearData,
  exportModelBom,
  getBomTotalDosage,
  remoteManufactureData
} from '@/apis/todo/flowBusiness';
import CFileUploadAndTempDownload from '@/businessComponents/CFileUploadAndTempDownload/index.vue';
import { isWeightUnit, empty } from '@/utils';
import { useExport } from '@/hooks/useExport';
import type { GetSupplierFormDetailResult } from '@/apis/supplier/model/supplierModel';
import commonConfig from '@/config';

interface ProductBomListProps {
  formNo: string;
  nodeCode?: string;
  readonly?: boolean;
  supplierFormInfo?: GetSupplierFormDetailResult;
}

const props = withDefaults(defineProps<ProductBomListProps>(), {
  readonly: false
});
const { handleExportFile } = useExport();

function getTableButtonsConfig(row: any): TableButtonItem[] {
  return [
    {
      text: '编辑',
      onClick: () => handleAddBom(row)
    },
    {
      text: '删除',
      onClick: () => handleDeleteBom(row.nodeNo)
    }
  ];
}
const { createMessage, createConfirm } = useMessage();

const materialDialogVisible = ref(false);
const nodeItem = ref();
const handleAddBom = (row?: any) => {
  // 新增BOM
  materialDialogVisible.value = true;
  nodeItem.value = row || null;
};
const handleDeleteBom = (node: string) => {
  //
  createConfirm('提示', '确认删除该物料？', {
    iconType: 'warning',
    confirmButtonText: '删除'
  }).then(() => {
    remoteManufactureData(node).then(() => {
      createMessage.success('删除成功！');
      handleRefresh();
    });
  });
};
const tableFieldsSetting: TableFieldsSettingType[] = [
  {
    title: '物料名称',
    titleTips: '填写材质名称，如钢、铝、塑料等，需为单一均质材料的名称',
    field: 'nodeName'
  },
  {
    title: '材料类别或牌号',
    titleTips: '非必填，可填写材质的类别或牌号，如钢材，S50C等',
    field: 'materialCategory'
  },
  {
    title: '用量',
    field: 'dosage',
    slot: 'dosageSlot',
    headerSlot: 'dosageHeaderSlot',
    align: 'right'
  },
  {
    title: '备注',
    titleTips: '非必填，可填写加工工艺或具体的材质型号',
    field: 'remark'
  },
  {
    title: '操作',
    field: 'op',
    width: 120,
    slot: 'op'
  }
];
const tableFieldsSettingReadonly: TableFieldsSettingType[] = [
  {
    title: '物料名称',
    titleTips: '填写材质名称，如钢、铝、塑料等，需为单一均质材料的名称',
    field: 'nodeName'
  },
  {
    title: '材料类别或牌号',
    titleTips: '非必填，可填写材质的类别或牌号，如钢材，S50C等',
    field: 'materialCategory'
  },
  {
    title: '用量',
    field: 'dosage',
    slot: 'dosageSlot',
    headerSlot: 'dosageHeaderSlot',
    align: 'right'
  },
  {
    title: '备注',
    titleTips: '非必填，可填写加工工艺或具体的材质型号',
    field: 'remark'
  }
];

const extraTableOption = {
  scrollY: { enabled: true },
  maxHeight: '460px',
  rowConfig: { height: 44 }
};

/**
 * 是否已导入数据
 */
const isBomImported = ref();

/**
 * 加载数据
 */
function loadData() {
  return getSupplierListBom(props.formNo).then(res => {
    // 获取bom总重量
    getBomTotalDosageFn();
    if (res.length) {
      isBomImported.value = true;
    } else {
      isBomImported.value = false;
    }
    return {
      records: res,
      total: res.length
    };
  });
}

const bomTotalDosage = ref();
async function getBomTotalDosageFn() {
  try {
    bomTotalDosage.value = await getBomTotalDosage(props.formNo);
  } catch (error) {
    console.log('error', error);
    bomTotalDosage.value = undefined;
  }
}

/**
 * 清空loading
 */
const clearLoading = ref(false);

/**
 * 清空模型数据
 */
function handleClearData() {
  createConfirm('提示', '清除后不可恢复，是否继续？', {
    iconType: 'warning'
  }).then(async () => {
    try {
      clearLoading.value = true;
      await postClearData(props.formNo);
      createMessage.success('清空成功！');
      clearLoading.value = false;
      handleRefresh();
    } catch (error) {
      console.log('error', error);
      clearLoading.value = false;
    }
  });
}

const tableRef = ref();
/**
 * 刷新
 */
function handleRefresh() {
  tableRef.value?.refresh();
}

const handleExport = () => {
  handleExportFile(exportModelBom, props.formNo);
};
</script>

<style lang="scss" scoped>
.product-bom-list {
  :deep(.vxe-table) {
    .vxe-tree--btn-wrapper {
      top: 6px;
      .vxe-tree--node-btn {
        color: #435970 !important;
      }
    }
  }
}

.product-bom-list__header {
  // height: 48px;
  padding-bottom: 16px;
}

.dosage-header-icon {
  color: #96a7b3;
  &:hover {
    color: #03ac82;
  }
}
</style>
